package arraytest;

import java.util.Arrays;

/*
冒泡排序
几轮冒泡 取决于元素的个数:轮次 = 数组长度-1
 */
public class ArrayTest6 {
    public static void main(String[] args) {
        //准备容器
        int[] arr = {11, 43, 22, 54, 37, 82, 7, 2, 17};
        System.out.println(Arrays.toString(arr));


        //冒泡的通用代码
        for (int j = 0; j < arr.length - 1; j++) {//冒泡轮次
            for (int i = 0; i < arr.length - 1 - j; i++) {
                //拿i元素和i+1元素进行比较
                if (arr[i] > arr[i + 1]) {
                    //满足 --> 交换
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }

            System.out.println("冒泡结束 : " + Arrays.toString(arr));
        }
            //第一轮冒泡
        mothod(arr);
    }

    private static void mothod(int[] arr) {
        for (int i = 0; i < arr.length - 1 - 0; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第一轮冒泡 : " + Arrays.toString(arr));
        for (int i = 0; i < arr.length - 1 - 1; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第二轮冒泡 : " + Arrays.toString(arr));

        for (int i = 0; i < arr.length - 1 - 2; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第三轮冒泡 : " + Arrays.toString(arr));

        for (int i = 0; i < arr.length - 1 - 3; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第四轮冒泡 : " + Arrays.toString(arr));

        for (int i = 0; i < arr.length - 1 - 4; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第五轮冒泡 : " + Arrays.toString(arr));

        for (int i = 0; i < arr.length - 1 - 5; i++) {
            //拿i元素和i+1元素进行比较
            if (arr[i] > arr[i + 1]) {
                //满足 --> 交换
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第六轮冒泡 : " + Arrays.toString(arr));
    }
}

